package 二叉树的层序遍历;

import java.util.*;

/**
 * @author: zhengtao
 * @description: 二叉树的层平均值
 * @version: 1.0
 * @date: 2022/10/29  14:19
 */
public class Demo637 {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> res=new ArrayList<>();
        if(root==null){
            return res;
        }
        Queue<TreeNode> queue=new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()){
            List<Integer> temp=new ArrayList<>();
            int size=queue.size();
            while (size-->0){
                TreeNode poll = queue.poll();
                temp.add(poll.val);
                if(poll.left!=null){
                    queue.add(poll.left);
                }
                if(poll.right!=null){
                    queue.add(poll.right);
                }
            }
            double sum=0;
            for (Integer integer : temp) {
                sum+=integer;
            }

            res.add(  sum / temp.size());
        }
       return  res;
    }

    /**
     * Definition for a binary tree node.
     * */
      public class TreeNode {
          int val;
          TreeNode left;
          TreeNode right;
          TreeNode() {}
          TreeNode(int val) { this.val = val; }
          TreeNode(int val, TreeNode left, TreeNode right) {
              this.val = val;
              this.left = left;
              this.right = right;
          }
      }

}
